/**
 * 飞行棋游戏前端应用
 */

// 登录组件
const Login = {
    template: `
        <div class="auth-container">
            <div class="auth-header">
                <h2>用户登录</h2>
            </div>
            <form class="auth-form" @submit.prevent="handleLogin">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" v-model="username" required placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" v-model="password" required placeholder="请输入密码">
                </div>
                <div v-if="message" class="error-message">{{ message }}</div>
                <button type="submit" :disabled="loading">
                    {{ loading ? '登录中...' : '登录' }}
                </button>
                <div class="form-footer">
                    <p>还没有账号？ <a href="#" @click.prevent="$emit('switch-form', 'register')">立即注册</a></p>
                </div>
            </form>
        </div>
    `,
    data() {
        return {
            username: '',
            password: '',
            loading: false,
            message: ''
        };
    },
    methods: {
        handleLogin() {
            this.loading = true;
            this.message = '';
            
            AuthService.login(this.username, this.password)
                .then(() => {
                    this.$emit('login-success');
                })
                .catch(error => {
                    this.loading = false;
                    if (error.response && error.response.data) {
                        this.message = error.response.data.message || '登录失败，请检查用户名和密码';
                    } else {
                        this.message = '登录失败，请稍后再试';
                    }
                });
        }
    }
};

// 注册组件
const Register = {
    template: `
        <div class="auth-container">
            <div class="auth-header">
                <h2>用户注册</h2>
            </div>
            <form class="auth-form" @submit.prevent="handleRegister">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" v-model="username" required placeholder="请输入3-20个字符的用户名">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" v-model="password" required placeholder="请输入6-40个字符的密码">
                </div>
                <div class="form-group">
                    <label for="email">邮箱 (可选)</label>
                    <input type="email" id="email" v-model="email" placeholder="请输入有效的邮箱地址">
                </div>
                <div v-if="message" class="error-message">{{ message }}</div>
                <button type="submit" :disabled="loading">
                    {{ loading ? '注册中...' : '注册' }}
                </button>
                <div class="form-footer">
                    <p>已有账号？ <a href="#" @click.prevent="$emit('switch-form', 'login')">立即登录</a></p>
                </div>
            </form>
        </div>
    `,
    data() {
        return {
            username: '',
            password: '',
            email: '',
            loading: false,
            message: ''
        };
    },
    methods: {
        handleRegister() {
            // 简单的表单验证
            if (this.username.length < 3 || this.username.length > 20) {
                this.message = '用户名长度必须在3到20个字符之间';
                return;
            }
            
            if (this.password.length < 6 || this.password.length > 40) {
                this.message = '密码长度必须在6到40个字符之间';
                return;
            }
            
            if (this.email && !this.validateEmail(this.email)) {
                this.message = '请输入有效的邮箱地址';
                return;
            }
            
            this.loading = true;
            this.message = '';
            
            AuthService.register(this.username, this.password, this.email)
                .then(response => {
                    this.loading = false;
                    alert('注册成功！请登录');
                    this.$emit('switch-form', 'login');
                })
                .catch(error => {
                    this.loading = false;
                    if (error.response && error.response.data) {
                        this.message = error.response.data.message || '注册失败，请稍后再试';
                    } else {
                        this.message = '注册失败，请稍后再试';
                    }
                });
        },
        validateEmail(email) {
            const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(String(email).toLowerCase());
        }
    }
};

// 游戏大厅组件
const GameHall = {
    template: `
        <div class="game-hall">
            <nav class="navbar navbar-expand-lg">
                <div class="container">
                    <a class="navbar-brand" href="#">飞行棋游戏</a>
                    <div class="user-info ml-auto">
                        <div class="user-avatar">{{ userInitial }}</div>
                        <span class="username">{{ user.username }}</span>
                        <button class="btn btn-light btn-sm ms-3" @click="logout">退出</button>
                    </div>
                </div>
            </nav>
            
            <div class="container mt-4">
                <div class="row">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">个人信息</div>
                            <div class="card-body">
                                <p><strong>用户名：</strong> {{ user.username }}</p>
                                <p><strong>邮箱：</strong> {{ user.email || '未设置' }}</p>
                                <p><strong>游戏场次：</strong> {{ userProfile.gamesPlayed || 0 }}</p>
                                <p><strong>获胜场次：</strong> {{ userProfile.gamesWon || 0 }}</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <span>房间列表</span>
                                <button class="btn btn-primary btn-sm">创建房间</button>
                            </div>
                            <div class="card-body">
                                <p>暂无可用房间</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `,
    data() {
        return {
            user: AuthService.getCurrentUser(),
            userProfile: {
                gamesPlayed: 0,
                gamesWon: 0
            }
        };
    },
    computed: {
        userInitial() {
            return this.user && this.user.username ? this.user.username.charAt(0).toUpperCase() : '?';
        }
    },
    mounted() {
        this.fetchUserProfile();
    },
    methods: {
        fetchUserProfile() {
            axios.get('/api/user/profile')
                .then(response => {
                    this.userProfile = response.data;
                })
                .catch(error => {
                    console.error('获取用户信息失败:', error);
                });
        },
        logout() {
            AuthService.logout();
            this.$emit('logout');
        }
    }
};

// 主应用
new Vue({
    el: '#app',
    template: `
        <div>
            <template v-if="!isLoggedIn">
                <component :is="currentForm" @switch-form="switchForm" @login-success="onLoginSuccess"></component>
            </template>
            <template v-else>
                <game-hall @logout="onLogout"></game-hall>
            </template>
        </div>
    `,
    data: {
        currentForm: 'login',
        isLoggedIn: AuthService.isLoggedIn()
    },
    components: {
        'login': Login,
        'register': Register,
        'game-hall': GameHall
    },
    methods: {
        switchForm(form) {
            this.currentForm = form;
        },
        onLoginSuccess() {
            this.isLoggedIn = true;
        },
        onLogout() {
            this.isLoggedIn = false;
            this.currentForm = 'login';
        }
    }
}); 